package user.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.*;
import org.springframework.stereotype.Service;
import user.client.CarrierClient;
import user.mapper.RoleMapper;
import user.mapper.UserMapper;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    CarrierClient carrierClient;

    public boolean existsByUsername(String userName) {
        QueryWrapper q = new QueryWrapper<>();
        q.eq("user_name",userName);
        return userMapper.exists(q);
    }

    public boolean existsByEmail(String email) {
        QueryWrapper q = new QueryWrapper<>();
        q.eq("email",email);
        return userMapper.exists(q);
    }

    public void save(User user) {
        userMapper.insert(user);
        if (user.getRoleId()==3){
            Carrier c = new Carrier();
            c.setUserId(user.getId());
            carrierClient.insert(c);
        }
    }

    public int updateUserInfo(User d) {
        return userMapper.updateById(d);
    }

    public List<User> getInfo(Long roleId) {
        QueryWrapper q = new QueryWrapper<>();
        if(roleId!=null)q.eq("role_id",roleId);
        List<User> ul = userMapper.selectList(q);
        ul.stream().map(user -> moreDetail(user)).collect(Collectors.toList());
        return ul;
    }

    public void delUser(Long id) {
        userMapper.deleteById(id);
    }

    public User getDetail(Long id) {
        User u = userMapper.selectById(id);
        u = moreDetail(u);
        return u;
    }

    private User moreDetail(User u){
        if(u.getRoleId()==3) {
            Carrier c = carrierClient.selectCarrierByUser(u.getId());
            u.setCarrier(c);
        }
        Role r = roleMapper.selectOne(new QueryWrapper<Role>().eq("id", u.getRoleId()));
        u.setRole(r);
        return u;
    }



    public User addDriver(User u) {
        userMapper.insert(u);
        return u;
    }

    public List<User> selectDriver(int i, Long id) {
        if(i==0){
            return userMapper.selectList(new QueryWrapper<User>().inSql("id", "SELECT driver_id FROM carrier_driver WHERE carrier_id = " + id));
        }else
            return userMapper.selectList(new QueryWrapper<User>().inSql("id", "SELECT driver_id FROM carrier_driver WHERE state = 0 and carrier_id = " + id));
    }
}
